import 'package:flutter/material.dart';
import 'package:flutter_animation/widget/ball/ball-model.dart';

class RunBall extends StatefulWidget {
  @override
  _RunBallState createState() => _RunBallState();
}

class _RunBallState extends State<RunBall> with SingleTickerProviderStateMixin {
  AnimationController controller;
  var _ball = Ball(
    color: Colors.blueAccent,
    r: 10,
    aY: 0.1,
    vX: 2,
    vY: -2,
    x: 40.0 + 140,
    y: 200.0 + 100,
  );
  var _area = Rect.fromLTRB(0 + 40.0, 0 + 200.0, 280 + 40.0, 200 + 200.0);

  @override
  Widget build(BuildContext context) {
    Widget child = Scaffold(
      body: CustomPaint(
        painter: RunBallView(
          _ball,
          _area,
        ),
      ),
    );

    return GestureDetector(
      child: child,
      onTap: () {
        controller.forward();
      },
    );
  }

  @override
  void initState() {
    controller =
        AnimationController(duration: Duration(days: 999 * 365), vsync: this);
    controller.addListener(_render);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  //渲染方法，更新状态
  void _render() {
    updateBall();
    setState(() {});
  }

  void updateBall() {
    _ball.x += _ball.vX;
    _ball.y += _ball.vY;
    _ball.vX += _ball.aX;
    _ball.vY += _ball.aY;

    //限定下边界
    if (_ball.y > _area.bottom - _ball.r) {
      _ball.y = _area.bottom - _ball.r;
      _ball.vY = -_ball.vY;
      // _ball.color = randomRGB(); //碰撞后随机色
    }
    //限定上边界
    if (_ball.y < _area.top + _ball.r) {
      _ball.y = _area.top + _ball.r;
      _ball.vY = -_ball.vY;
      // _ball.color = randomRGB(); //碰撞后随机色
    }

    //限定左边界
    if (_ball.x < _area.left + _ball.r) {
      _ball.x = _area.left + _ball.r;
      _ball.vX = -_ball.vX;
      // _ball.color = randomRGB(); //碰撞后随机色
    }

    //限定右边界
    if (_ball.x > _area.right - _ball.r) {
      _ball.x = _area.right - _ball.r;
      _ball.vX = -_ball.vX;
      // _ball.color = randomRGB(); //碰撞后随机色
    }
  }
}
